import axios from 'axios'
import React, { useEffect, useState } from 'react'
import { Navigate, useLocation, useNavigate, useParams } from 'react-router-dom'
import { Notify, ActionBar, Popup, Typography, Stepper } from 'react-vant'
import { CarItemType, ListItemType } from '../../types'
import { CartO, ChatO, ShopO } from '@react-vant/icons'
import { useAppDispatch } from '../../app/hooks'
import { addCar } from '../../app/car/carSlice'
import { useCar } from '../../hooks'

const Index: React.FC = () => {
	// 详情数据
	const [item, setItem] = useState<ListItemType | null>(null)
	// 规格弹框状态
	const [visible, setVisible] = useState(false)
	// 当前商品数量
	const [count, setCount] = useState(1)
	//  获取动态路由参数
	const { id } = useParams()
	const naviagate = useNavigate()
	const dispatch = useAppDispatch()
	// 使用已定义hooks
	const { totalCount } = useCar()
	// 数据请求
	const fetchDetail = async () => {
		const resp = await axios.get('/api/detail/' + id)
		const { code, data, message } = resp.data;
		if (code === 200) {
			setItem(data)
			Notify.show({ type: "success", message })
		} else {
			Notify.show({ type: "danger", message })
		}
	}

	// 点击加入购物车
	const handleAddCar = () => {
		if (item) {
			const data: CarItemType = {
				...item,
				count,
				isChecked: false
			}
			dispatch(addCar(data))
			setVisible(false);
		}
	}

	useEffect(() => {
		fetchDetail()
	}, [])

	if (!item) {
		return <div>数据拼命加载中...</div>
	}

	return (
		<div>
			<div>
				<img src={item.url} style={{ width: '100%' }} alt="" />
				<h3>{item.title}</h3>
				<p>{item.desc}</p>
				<p>￥： {item.price}</p>
			</div>

			<div>
				<ActionBar>
					<ActionBar.Icon icon={<ChatO />} badge={{ dot: true }} text='客服' />
					<ActionBar.Icon icon={<CartO />} badge={{ content: totalCount }} text='购物车' onClick={() => naviagate('/shopcar')} />
					<ActionBar.Icon icon={<ShopO />} text='店铺' />
					<ActionBar.Button type='warning' text='加入购物车' onClick={() => setVisible(true)} />
					<ActionBar.Button type='danger' text='立即购买' />
				</ActionBar>
			</div>
			<Popup
				visible={visible}
				position="bottom"
				round
				onClose={() => {
					setVisible(false)
				}}
			>
				<div style={{ padding: '10px' }}>
					<dl style={{ display: 'flex' }}>
						<dt>
							<img src={item.url} alt="" />
						</dt>
						<dd>
							<Typography.Title level={3}>{item.title}</Typography.Title>
							<Typography.Text >{item.desc}</Typography.Text>
						</dd>
					</dl>

					<div>单价: ￥{item.price}</div>

					<div>数量:  <Stepper min={1} value={count} onChange={v => v && setCount(v)} /></div>

					<div style={{ height: 50 }}>
						<ActionBar>
							<ActionBar.Button type='warning' text='加入购物车' onClick={() => handleAddCar()} />
						</ActionBar>
					</div>
				</div>
			</Popup>
		</div>
	)
}

export default Index